var http = require("http"),
    JSONUtil = require("./jsonUtil"),
    url = require("url"),
    config = require("../config.js"),
    crypto = require("crypto"),
    qs = require("querystring");

var signAlgorithm = function (_signUrl, params) {
    var arr = [];
    for (key in params) {
        arr.push(key + "=" + params[key]);
    }
    var sortString = arr.sort();
    var MosaicParam = "";
    for (var i = 0; i < sortString.length; i++) {
        MosaicParam += sortString[i] + "_";
    }
    MosaicParam = MosaicParam.substring(0, MosaicParam.length - 1);
    var urlParam = _signUrl + "_" + MosaicParam + "_" + config.user.secretKey;
    var encodeUrlParam = encodeURIComponent(urlParam);
    var md5 = crypto.createHash("md5");
    md5.update(encodeUrlParam)
    var md5String = md5.digest("hex");
    return md5String
};

var httpUtil = {
    signAlgorithm: signAlgorithm,
    POST: function (_url, _subUrl, params, cb) {
        _url += _subUrl;
        if (_url.indexOf("?") > -1) {
            _url += "&";
        } else {
            _url += "?";
        }
        _url += "appkey=" + config.user.appkey;
        _url += "&sign=" + signAlgorithm(_subUrl, qs.parse(_url.slice(_url.indexOf("?") + 1, _url.length)));
        _url = url.parse(_url, true);
        var opt = {
            method: "POST",
            host: _url.hostname,
            port: _url.port,
            path: _url.path,
            keepAlive: true,
            headers: {
                "Content-Type": 'application/x-www-form-urlencoded',
                "Accept": "application/json"
            }
        };
        var req = http.request(opt, function (res) {
            if (res.statusCode == 200) {
                var jsonUtil = new JSONUtil();
                jsonUtil.parseResponse(res, function (error, data) {
                    cb(error, data);
                });
            } else {
                var error = "call remote method error";
                cb(error)
            }
        });
        if (params) {
            req.write(qs.stringify(params));
        }
        req.end();
    },
    GET: function (_url, _subUrl, params, cb) {
        _url += _subUrl;
        if (_url.indexOf("?") > -1) {
            _url += "&";
        } else {
            _url += "?";
        }
        _url += "appkey=" + config.user.appkey;
        if (params) {
            _url += "&" + qs.stringify(params);
        }
        _url += "&sign=" + signAlgorithm(_subUrl, qs.parse(_url.slice(_url.indexOf("?") + 1, _url.length)));
        http.get(_url, function (res) {
            if (res.statusCode == 200) {
                var jsonUtil = new JSONUtil();
                jsonUtil.parseResponse(res, function (error, data) {
                    cb(error, data);
                });
            } else {
                var error = "call remote method error";
                cb(error)
            }
        });
    }
};

module.exports = httpUtil;